<?php
namespace app\farm\model;

use app\BaseModel;
use app\farm\model\BalanceWater;

use app\farm\model\User;
use app\shop\model\IntegralLog;
use longbingcore\wxcore\PayModel;
use think\facade\Db;

class SendOrder extends BaseModel
{
    //定义表名
    protected $name = 'lbfarm_send_order';


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);;

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-14 15:45
     * @功能说明:添加关联
     */
    public function updateSome($id,$data){

        $server = new \app\farm\server\Claim();

        $claim_text_model = new ClaimText();

        $source_text_model= new LandSourceText();

        $monitor_text_model= new MonitorText();

        $server->addObserver($claim_text_model);

        $server->addObserver($source_text_model);

        $server->addObserver($monitor_text_model);

        $server->notify($id,$data);

        return true;

    }

    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page=10){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-16 15:39
     * @功能说明:回调
     */
    public function orderResult($order_code,$transaction_id){

        $order = $this->dataInfo(['order_code'=>$order_code]);

        if(!empty($order)&&$order['pay_type']==1){

            $update = [

                'pay_time' => time(),

                'pay_type' => 2,

                'transaction_id' => $transaction_id
            ];

            $this->dataUpdate(['id'=>$order['id']],$update);
            //扣除余额
            if($order['balance']>0){

                $water_model = new BalanceWater();

                $type = $order['type']==1?3:9;

                $res = $water_model->addWater($order,$type,0);

                if($res==0){

                    Db::rollback();

                }
            }
            //添加流水
            $water_model = new FinanceWater();
            //1认养 2土地
            $water_type  = $order['type']==1?10:14;

            $water_model->addWater($order['id'],$water_type,1,0);

            $this->paySendMsg($order);

        }

        return true;

    }






    /**
     * @author chenniang
     * @DataTime: 2021-04-01 09:51
     * @功能说明:公众号给农场主发送通知
     */
    public function paySendMsg($order){

        $uniacid = $order['uniacid'];

        $x_config = longbingGetAppConfig($uniacid);

        if(empty($x_config['gzh_appid'])||empty($x_config['gzh_tplid'])){

            return false;
        }

        $farmer_model = new Farmer();

        $user_id = $farmer_model->where(['id'=>$order['farmer_id']])->value('user_id');

        if(empty($user_id)){

            return false;
        }

        $user_model = new User();

        $openid = $user_model->where(['id'=>$user_id])->value('openid');

        $access_token = longbingGetAccessToken($uniacid);

        $page =$order['type']==1?"claim/pages/order/detail?id=".$order['id']."&tab=2&notice=1":"land/pages/order/detail?id=".$order['id']."&tab=2&notice=1";
        //post地址
        $url  = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token={$access_token}";

        $data = [
            //用户小程序openid
            'touser' => $openid,

            'mp_template_msg' => [
                //公众号appid
                'appid' => $x_config['gzh_appid'],

                "url"   => "http://weixin.qq.com/download",
                //公众号模版id
                'template_id' => $x_config['gzh_tplid'],

                'miniprogram' => [
                    //小程序appid
                    'appid'   => $x_config['appid'],
                    //跳转小程序地址
                    'page'    => $page,
                ],
                'data' => array(

//                    'first' => array(
//
//                        'value' => $store_name.'技师，您有一笔新的订单',
//
//                        'color' => '#93c47d',
//                    ),
                    //服务名称
                    'keyword1' => array(

                        'value' => $order['order_code'],

                        'color' => '#93c47d',
                    ),
                    //下单人
                    'keyword2' => array(
                        //内容
                        'value' => date('Y-m-d H:i',$order['start_time']).'~'.date('Y-m-d H:i',$order['end_time']),

                        'color' => '#0000ff',
                    ),
                    'keyword3' => array(
                        //内容
                        'value' => $order['text'],

                        'color' => '#0000ff',
                    )

                )
            ],
        ];

        $data = json_encode($data);

        $tmp = [

            'url'  => $url,

            'data' => $data,
        ];
        $rest = lbCurlPost($tmp['url'], $tmp['data']);

        $rest = json_decode($rest, true);

        return $rest;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-09 13:45
     * @功能说明:订单收货
     */
    public function sendOrderReceiving($order,$hx_user=0,$hx_admin=0,$hx_time=0){

        $order_id = $order['id'];

        $update = [

            'pay_type'       => 7,

            'receiving_time' => !empty($hx_time)?$hx_time:time(),

            'hx_user'        => $hx_user,

            'hx_admin'       => $hx_admin
        ];

        Db::startTrans();

        $res = $this->dataUpdate(['id'=>$order_id],$update);

        if($res==0){

            Db::rollback();

            return ['code'=>500,'msg'=>'收货失败'];
        }

        $water_model = new FinanceWater();

        $water_type  = $order['type']==1?10:14;

        $dis = [

            'type'     => $water_type,

            'order_id' => $order_id
        ];
        //将流水记录修改为可提现状态
        $res = $water_model->dataUpdate($dis,['cash_status'=>1]);

        if($res==0){

            Db::rollback();

            return ['code'=>500,'msg'=>'收货失败1'];
        }
        //暂时只执行认养配送的
        if($order['type']==1){

            $order_model = $order['type']==1?new ClaimOrder():new LandOrder();
            //有可能是自提
            $order_model->dataUpdate(['id'=>$order['order_id']],['pay_type'=>3]);

            $top_order  = $order_model->dataInfo(['id'=>$order['order_id']]);

            $count = $this->where(['order_id'=>$order['order_id'],'type'=>$order['type'],'pay_type'=>7])->count();

            if($count>=$top_order['send_times']){

                $order_model->dataUpdate(['id'=>$top_order['id']],['pay_type'=>7]);
            }

        }

        $i_type  = $order['type']==1?8:9;

        $integral_model = new IntegralLog();
        //赠送积分
        $integral_model->integralUserAdd($order['user_id'],$order['get_integral'],$order['uniacid'],2,$i_type,$order['id']);

        Db::commit();

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-01 10:13
     * @功能说明:超时自动退款
     */
    public function autoCancelOrder($uniacid,$user_id=0){

        $where[] = ['uniacid','=',$uniacid];

        $where[] = ['pay_type','=',3];

        $where[] = ['auto_receiving_time','<',time()];

        if(!empty($user_id)){

            $dis[] = ['user_id','=',$user_id];
        }

        $order = $this->where($where)->select()->toArray();

        if(!empty($order)){

            foreach ($order as $value){

                $this->sendOrderReceiving($value,0,0,$value['auto_receiving_time']);

            }

        }

        return true;
    }



    /**
     * @author chenniang
     * @DataTime: 2021-04-01 10:13
     * @功能说明:退款
     */
    public function cancelOrder($order){

        Db::startTrans();

        $res = $this->dataUpdate(['id'=>$order['id'],'pay_type'=>1],['pay_type'=>-1,'cancel_time'=>time()]);

        if($res!=1){

            Db::rollback();

            return ['code'=>500,'msg'=>'取消失败'];
        }

        $claim_model = new Claim();

        $claim = $claim_model->dataInfo(['id'=>$order['goods_id']]);
        //加销量减库存
        $update = [

            'stock'    => $claim['stock'] +1,

            'sale_num' => $claim['sale_num']-1,

            'lock'     => $claim['lock']+1

        ];

        $res = $claim_model->dataUpdate(['id'=>$claim['id'],'lock'=>$claim['lock']],$update);

        if($res==0){

            Db::rollback();

            return ['code'=>500,'msg'=>'取消失败'];

        }

        Db::commit();

        return true;

    }


    /**
     * @param $order_id
     * @param $type 1认养 2土地
     * @功能说明:指定订单的配送订单
     * @author chenniang
     * @DataTime: 2022-02-16 14:37
     */
    public function orderSendOrder($order_id,$type=1,$page=10){

        $dis[] = ['order_id','=',$order_id];

        $dis[] = ['pay_time','>',0];

        $dis[] = ['type','=',$type];

        $send_order_model = new SendOrder();

        $data = $send_order_model->dataList($dis,$page);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['time_text'] = date('Y-m-d H:i',$v['start_time']).'~'.date('H:i',$v['end_time']);

                $v['create_time']    = date('Y-m-d H:i:s',$v['create_time']);

                $v['pay_time']       = $v['pay_time']>0?date('Y-m-d H:i:s',$v['pay_time']):0;

                $v['send_time']      = $v['send_time']>0?date('Y-m-d H:i:s',$v['send_time']):0;

                $v['receiving_time'] = $v['receiving_time']>0?date('Y-m-d H:i:s',$v['receiving_time']):0;

                $v['refund_time']    = $v['refund_time']>0?date('Y-m-d H:i:s',$v['refund_time']):0;
            }
        }
        $dis = [

            'order_id' => $order_id,

            'type'     => $type
        ];
        //已经申请的配送次数
        $data['send_count'] = $send_order_model->where($dis)->where('pay_type','>',1)->count();

        return $data;

    }


    /**
     * @param $order
     * @功能说明:配送订单退款
     * @author chenniang
     * @DataTime: 2022-08-22 10:47
     */
    public function refundCash($send_order,$payConfig){

        if($send_order['send_type']==1||$send_order['pay_price']<=0){

            return true;

        }

        if($send_order['pay_model']==1){

            $response = orderRefundApi($payConfig,$send_order['pay_price'],$send_order['pay_price'],$send_order['transaction_id']);

            if ( isset( $response[ 'return_code' ] ) && isset( $response[ 'result_code' ] ) && $response[ 'return_code' ] == 'SUCCESS' && $response[ 'result_code' ] == 'SUCCESS' ) {

                $response['out_refund_no'] = !empty($response['out_refund_no'])?$response['out_refund_no']:$send_order['order_code'];

                $this->dataUpdate(['id'=>$send_order['id']],['refund_code'=>$response['out_refund_no']]);

            }else {
                //失败就报错
                $discption = !empty($response['err_code_des'])?$response['err_code_des']:$response['return_msg'];

                return ['code'=>500,'msg'=>$discption];

            }

        }elseif ($send_order['pay_model']==2){

            $water_model = new BalanceWater();

            $res = $water_model->addWater($send_order,4,1);

            if($res==0){

                return ['code'=>500,'msg'=>'退款失败2'];

            }
        }else{
            //支付宝
            $pay_model = new PayModel($payConfig);

            $res = $pay_model->aliRefund($send_order['transaction_id'],$send_order['pay_price']);

            if(isset($res['alipay_trade_refund_response']['code'])&&$res['alipay_trade_refund_response']['code']==10000){

                $this->dataUpdate(['id'=>$send_order['id']],['refund_code'=>$res['alipay_trade_refund_response']['out_trade_no']]);

            }else{

                return ['code'=>500,'msg'=> $res['alipay_trade_refund_response']['sub_msg']];

            }

        }

        return true;
    }






}